//
//  ListItem.m
//  FlyGift
//
//  Created by lanou3g on 15/7/17.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "ListItem.h"

#define kDeleteW 6
#define kItemFont 13
#define kItemSizeChangeAdded 2
#define padding 20
#define itemPerLine 4
#define kItemW (kScreenWidth-padding*(itemPerLine+1))/itemPerLine
#define kItemH 25

@implementation ListItem

/**
 *
 typedef enum{
 top = 0,
 bottom = 1
 }itemLocation;
 
 @interface ListItem : UIButton
 {
 @public
 NSMutableArray *locateView;
 NSMutableArray *topView;
 NSMutableArray *bottomView;
 }
 
 @property(nonatomic, strong)UIView *hitTextLabel;
 
 @property(nonatomic, strong)UIButton *deleBtn;
 
 @property(nonatomic, strong)UIButton *hiddenButton;
 
 @property(nonatomic, assign)itemLocation location;
 
 @property(nonatomic, copy)NSString *itemName;;
 
 
 // 两个手势
 @property(nonatomic, strong)UIPanGestureRecognizer *panGesture;
 
 @property(nonatomic, strong)UILongPressGestureRecognizer *longPressGesture;
 */

- (void)setItemName:(NSString *)itemName
{
    _itemName = itemName;
    // 按钮的一些基本属性设置
    [self setTitle:itemName forState:UIControlStateNormal];
    [self setTitleColor:KColor(111, 111, 111, 1) forState:UIControlStateNormal];
    self.titleLabel.font = [UIFont systemFontOfSize:kItemFont];
    self.layer.cornerRadius = 4.0;
    self.layer.borderColor = KColor(200, 200, 200, 1).CGColor;
    self.layer.borderWidth = 0.5;
    self.backgroundColor = [UIColor whiteColor];
    // 添加点击事件
    [self addTarget:self action:@selector(operationWithoutHidBtn) forControlEvents:UIControlEventTouchUpInside];
    
    
    // 轻拍手势
    self.panGesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panGestureAction:)];
    // 长按手势
    self.longPressGesture = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressGestureAction:)];
    // 需要长按的时间 最小为1.0s
    self.longPressGesture.minimumPressDuration = 1.0;
    // 手指按住允许移动的距离 (像素)
    self.longPressGesture.allowableMovement = 20;
    // 添加手势
    [self addGestureRecognizer:_longPressGesture];
    
    
    // 显示的第一个按钮是不能删除的
    if (![itemName isEqualToString:@"精选"])
    {
        if (!self.deleBtn)
        {
            // 点击出现的删除的小图标
            self.deleBtn = [[UIButton alloc]initWithFrame:CGRectMake(-kDeleteW+2, -kDeleteW + 2, 2*kDeleteW, 2*kDeleteW)];
            // 关掉交互
            self.deleBtn.userInteractionEnabled = NO;
            // 设置图片
            [self.deleBtn setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
            self.deleBtn.layer.cornerRadius = self.deleBtn.frame.size.width / 2;
            self.deleBtn.hidden = YES;
            self.deleBtn.backgroundColor = KColor(111, 111, 111, 1);
            [self addSubview:_deleBtn];
        }
    }
    
    if (!self.hiddenButton)
    {
        self.hiddenButton = [[UIButton alloc]initWithFrame:self.bounds];
        self.hiddenButton.hidden = NO;
        [self.hiddenButton addTarget:self action:@selector(operationWithHidBtn) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_hiddenButton];
    }
    
    
    // 添加一个通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(sortButtonAction) name:@"sortBtnAction" object:nil];
    
}


- (void)operationWithoutHidBtn
{
    if (self.location == top)
    {
        [self changeFromTopToBottom];
    }
    else if (self.location == bottom)
    {
        self.deleBtn.hidden = NO;
        [self addGestureRecognizer:self.panGesture];
        [self changeFromBottomToTop];
    }
}

#pragma mark - 被隐藏的文字显示出来的时候
- (void)operationWithHidBtn
{
    if (!self.hiddenButton.hidden)
    {
        if (self.location == top)
        {
            [self setTitleColor:kMainColor forState:UIControlStateNormal];
            
            if (self.operationBlock)
            {
                self.operationBlock(topViewClick,self.titleLabel.text,0);
            }
            // 动画效果
            [self animationForWholeView];
        }
        
        else if (self.location == bottom)
        {
            [self changeFromBottomToTop];
        }
    }
}



#pragma mark - 长按按钮手势触发的方法
- (void)longPressGestureAction:(UILongPressGestureRecognizer *)longPress
{
    if (self.hiddenButton.hidden == NO)
    {
        if (self.longpressBlock)
        {
            self.longpressBlock();
        }
        // 如果位置在上方的话 就添加手势
        if (self.location == top)
        {
            [self addGestureRecognizer:self.panGesture];
        }
    }
}


#pragma mark - 排序按钮的触发方法
- (void)sortButtonAction
{
    // 如果位置是在上边的话 切换删除小图标的状态
    if (self.location == top)
    {
        self.deleBtn.hidden = !self.deleBtn.hidden;
    }
    // 调节排序图标的状态
    self.hiddenButton.hidden = !self.hiddenButton.hidden;
    
    // 如果存在手势 就移除
    if (self.gestureRecognizers)
    {
        [self removeGestureRecognizer:self.panGesture];
    }
    
    // 如果按钮是隐藏状态 并且是显示在上边的话 就添加手势
    if (self.hiddenButton.hidden && self.location == top)
    {
        [self addGestureRecognizer:_panGesture];
    }
    
}

#pragma mark - 动画移动部分

- (void)panGestureAction:(UIPanGestureRecognizer *)pan
{
    [self.superview exchangeSubviewAtIndex:[self.superview.subviews indexOfObject:self] withSubviewAtIndex:[[self.superview subviews] count] - 1];
    CGPoint translation = [pan translationInView:pan.view];
    CGPoint center = pan.view.center;
    center.x += translation.x;
    center.y += translation.y;
    pan.view.center = center;
    [pan setTranslation:CGPointZero inView:pan.view];
    
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:{
            CGRect itemFrame = self.frame;
            [self setFrame:CGRectMake(itemFrame.origin.x-kItemSizeChangeAdded, itemFrame.origin.y-kItemSizeChangeAdded, itemFrame.size.width+kItemSizeChangeAdded*2, itemFrame.size.height+kItemSizeChangeAdded*2)];
        }
            break;
        case UIGestureRecognizerStateChanged:{
            BOOL InTopView = [self whetherInAreaWithArray:topView Point:center];
            if (InTopView) {
                NSInteger indexX = (center.x <= kItemW+2*padding)? 0 : (center.x - kItemW-2*padding)/(padding+kItemW) + 1;
                NSInteger indexY = (center.y <= kItemH+2*padding)? 0 : (center.y - kItemH-2*padding)/(padding+kItemH) + 1;
                
                NSInteger index = indexX + indexY*itemPerLine;
                index = (index == 0)? 1:index;
                [locateView removeObject:self];
                [topView insertObject:self atIndex:index];
                locateView = topView;
                [self animationForTopView];
                if (self.operationBlock) {
                    self.operationBlock(FromTopToTop,self.titleLabel.text,(int)index);
                }
            }
            else if (!InTopView && center.y < [self TopViewMaxY]+50) {
                [locateView removeObject:self];
                [topView insertObject:self atIndex:topView.count];
                locateView = topView;
                [self animationForTopView];
                if (self.operationBlock) {
                    self.operationBlock(FromTopToTopLast,self.titleLabel.text,0);
                }
            }
            else if (center.y > [self TopViewMaxY]+50){
                [self changeFromTopToBottom];
            }
        }
            break;
        case UIGestureRecognizerStateEnded:
            [self animationForWholeView];
            break;
        default:
            break;
    }

}



-(void)changeFromTopToBottom{
    [locateView removeObject:self];
    [bottomView insertObject:self atIndex:0];
    locateView = bottomView;
    self.location = bottom;
    self.deleBtn.hidden = YES;
    [self removeGestureRecognizer:self.panGesture];
    if (self.operationBlock) {
        self.operationBlock(FromTopToBottomHead,self.titleLabel.text,0);
    }
    [self animationForWholeView];
}

-(void)changeFromBottomToTop{
    [locateView removeObject:self];
    [topView insertObject:self atIndex:topView.count];
    locateView = topView;
    self.location = top;
    if (self.operationBlock) {
        self.operationBlock(FromBottomToTopLast,self.titleLabel.text,0);
    }
    [self animationForWholeView];
}

- (BOOL)whetherInAreaWithArray:(NSMutableArray *)array Point:(CGPoint)point{
    int row = (array.count%itemPerLine == 0)? itemPerLine : array.count%itemPerLine;
    int column =  (int)(array.count-1)/itemPerLine+1;
    if ((point.x > 0 && point.x <=kScreenWidth &&point.y > 0 && point.y <= (kItemH + padding)*(column-1)+padding)||
        (point.x > 0 && point.x <= (row*(padding+kItemW)+padding)&& point.y > (kItemH + padding)*(column -1)+padding && point.y <= (kItemH+padding) * column+padding)){
        return YES;
    }
    return NO;
}

- (unsigned long)TopViewMaxY{
    unsigned long y = 0;
    y = ((topView.count-1)/itemPerLine+1)*(kItemH + padding) + padding;
    return y;
}

- (void)animationForTopView{
    for (int i = 0; i < topView.count; i++){
        if ([topView objectAtIndex:i] != self){
            [self animationWithView:[topView objectAtIndex:i] frame:CGRectMake(padding+(padding+kItemW)*(i%itemPerLine), padding+(kItemH + padding)*(i/itemPerLine), kItemW, kItemH)];
        }
    }
}
-(void)animationForBottomView{
    for (int i = 0; i < bottomView.count; i++) {
        if ([bottomView objectAtIndex:i] != self) {
            [self animationWithView:[bottomView objectAtIndex:i] frame:CGRectMake(padding+(padding+kItemW)*(i%itemPerLine), [self TopViewMaxY]+50+(kItemH+padding)*(i/itemPerLine), kItemW, kItemH)];
        }
    }
    [self animationWithView:self.hitTextLabel frame:CGRectMake(0,[self TopViewMaxY],kScreenWidth,30)];
}

- (void)animationForWholeView{
    for (int i = 0; i <topView.count; i++) {
        [self animationWithView:[topView objectAtIndex:i] frame:CGRectMake(padding+(padding+kItemW)*(i%itemPerLine), padding+(padding+kItemH)*(i/itemPerLine), kItemW, kItemH)];
    }
    for (int i = 0; i < bottomView.count; i++) {
        [self animationWithView:[bottomView objectAtIndex:i] frame:CGRectMake(padding+(padding+kItemW)*(i%itemPerLine), [self TopViewMaxY]+50+(kItemH+padding)*(i/itemPerLine), kItemW, kItemH)];
    }
    [self animationWithView:self.hitTextLabel frame:CGRectMake(0,[self TopViewMaxY],kScreenWidth,30)];
}

-(void)animationWithView:(UIView *)view frame:(CGRect)frame{
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionLayoutSubviews animations:^{
        [view setFrame:frame];
    } completion:^(BOOL finished){}];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



@end
